import React, { FC, useState, useEffect, useRef } from 'react';
import { connect } from 'react-redux';
import { Button, Toast } from 'antd-mobile-v2';
import { ConnectProps, ConnectState } from 'typings/connect';
import createDOMForm from '@/components/rc-form/createDOMForm';
import { WrappedFormClass } from 'rc-form';
import styles from './index.module.less';
import { parseFormData } from '@/plugins/form/form-render/utils/detail-parser';
import { BPMN_APPLY_NODE_ID } from '@/plugins/constant';
import ProcessSteps, {
  ProcessValidator,
  ProcessValidateResult
} from '@/components/ProcessSteps';
import { Prompt } from 'react-router-dom';
import {
  clearRouteBlocker,
  setRouteBlocker
} from '@/components/form-group/route-blocker';
import { getSearchName } from '@/utils/index';
import { getFromDetail } from '@/services/form-render';
import FormRender from '../widget-components';
import { useForm } from 'form-render';
import { mockJson } from '../mock';

const FormDetail: FC = (props: any) => {
  const id = props?.match?.params?.id || '';
  const form = useForm();

  const title = getSearchName('title');
  const [submitType, setSubmitType] = useState('');
  const [loading, setLoading] = useState(false);
  const formRef: React.MutableRefObject<any> = useRef(null);

  const [detailData, setDetailData] = useState({});
  const [schema, setSchema] = useState(mockJson);
  useEffect(() => {
    getFormDetailData(id);
  }, [id]);
  const getFormDetailData = async (id: string) => {
    try {
      const res = await getFromDetail(id);
      const data = res.data;
      setDetailData(data);
      const schemaJson = JSON.parse(data?.formMetadata);
      // console.log(
      //   '%data?.formMetadata=========={}',
      //   'color:green;font-size:18px',
      //   data?.formMetadata
      // );
      // console.log(
      //   '%cschemaJson',
      //   'color:green;font-size:18px;font-weight:bold',
      //   schemaJson
      // );
      setSchema(schemaJson);
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    console.log('form:', form);
    // test todo??
    // 表单回显
    form?.setValues({
      // input_A1ELWs: '1111111111',
      // number_HYqpwR: 21212,
      // 'date_gt-eNW': '2021-10-21'
    });
  }, []);

  const handleOk = (type: string) => {
    console.log('type:', type);
    const values = form.getValues();
    console.log('values:', values);
    form?.submit();
  };

  const onFinish = (value: any) => {
    console.log('onFinish:', value);
  };

  return (
    <div className={styles.applyWrap} style={{ height: window.screen.height }}>
      <div className={styles.applyPage}>
        <div className={styles.scrollWrap}>
          <div className={styles.applyForm}>
            <div className={styles.header}>
              <div className={styles.title}>{props.location?.query?.title}</div>
            </div>
            <div className={styles.formContent}>
              {schema && (
                <FormRender
                  // schema={schema}
                  schema={mockJson}
                  onFinish={onFinish}
                  form={form}
                  renderMode='edit'
                />
              )}

              {/* <div className={styles.applyFormProcess}>
                <ProcessSteps
                  ref={this.processRef}
                  setValidateMethod={this.setValidateMethod}
                  historyTask={state.historyTaskList}
                  form={props.form}
                  formData={state.formData}
                  formValues={this.state.formValues}
                  query={this.getSearchName()}
                  choosePersons={this.state.choosePersons}
                />
              </div>
               */}
            </div>
          </div>
        </div>
      </div>
      <div className={styles.footer}>
        {/* <Button
          onClick={() => handleOk('draft')}
          loading={submitType === 'draft' && loading}
        >
          保存草稿
        </Button> */}
        <Button
          onClick={() => handleOk('submit')}
          loading={submitType === 'submit' && loading}
          type='primary'
        >
          提交
        </Button>
      </div>
      <Prompt
        message={(nextRoute) => setRouteBlocker(props.history, nextRoute)}
      />
    </div>
  );
};

const mapStateToProps = ({ capproval, loading, common }: ConnectState) => {
  return {
    loading: loading.effects['capproval/startProcess'],
    formData: capproval.formData,
    userInfo: common?.userInfo
  };
};

export default connect(mapStateToProps)(FormDetail);
